package com.ja.openchat.ui.me;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.ui.contact.ContactChooseAdapter;
import com.ja.openchat.views.CustomEditText;
import com.ja.openchat.views.SideIndexBar;
import com.zy.openchat.core.model.contact.Section;
import com.zy.openchat.core.model.contact.SectionInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Common;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class RemoveCircleSettingUserActivity extends JaBaseActivity {


    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.slide)
    SideIndexBar slideBar;
    @BindView(R.id.tv_ok_right)
    TextView tv_ok_right;
    @BindView(R.id.et_search)
    CustomEditText etSearch;

    public static void startForResult(Activity context, ArrayList<UserInfo> chooseUsers,int requestCode){
        Intent intent = new Intent(context, RemoveCircleSettingUserActivity.class);
        intent.putExtra("chooseUsers",chooseUsers);
        context.startActivityForResult(intent,requestCode);
    }
    private ArrayList<UserInfo> chooseUsers;

    private ContactChooseAdapter contactChooseAdapter;
    private List<Section> sectionList = new ArrayList<>();
    private Map<Long, UserInfo> choosedDic = new HashMap<>();
    @Override
    public void initData() {
        setTitle(getString(R.string.select_members_remove));
        if(getIntent()!=null){
            if(getIntent().getSerializableExtra("chooseUsers")!=null){
                chooseUsers = (ArrayList<UserInfo>)getIntent().getSerializableExtra("chooseUsers");
            }
        }

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        contactChooseAdapter = new ContactChooseAdapter(R.layout.adapter_choose_contact_list, R.layout.adapter_section_contact_list, sectionList);
        recyclerView.setAdapter(contactChooseAdapter);
        contactChooseAdapter.setEmptyView(R.layout.status_center_empty_view_wrap);
        //索引事件
        slideBar.setOnIndexChangedListener((index, position) -> {
            for (int i = 0; i < sectionList.size(); i++) {
                if (sectionList.get(i).isHeader()) {
                    SectionInfo info = (SectionInfo) sectionList.get(i).getObject();
                    if (info.title.equals(String.valueOf(index.charAt(0)))) {
                        recyclerView.scrollToPosition(i);
                        break;
                    }
                }
            }
        });
        contactChooseAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (sectionList != null && sectionList.size() > 0 && position >= 0 && position < sectionList.size()) {
                    Object obj = sectionList.get(position).getObject();
                    if (obj instanceof UserInfo) {
                        UserInfo user = (UserInfo) obj;
                        if (choosedDic.get(user.id) != null) {
                            choosedDic.remove(user.id);
                        } else {
                            choosedDic.put(user.id, user);
                        }
                        contactChooseAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
        contactChooseAdapter.setOnChooseListener(new ContactChooseAdapter.OnChooseListener() {
            @Override
            public boolean isSignalMode() {
                return false;
            }

            @Override
            public boolean isChoose(UserInfo user) {
                return choosedDic.containsKey(user.id);
            }

            @Override
            public boolean showMask(UserInfo user) {
                return false;
            }
        });
        tv_ok_right.setVisibility(View.VISIBLE);
        tv_ok_right.setText(getString(R.string.ok_text));
        tv_ok_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!choosedDic.isEmpty()){
                    ArrayList<UserInfo> users = new ArrayList<>(choosedDic.values());
                    Intent intent = new Intent();
                    intent.putExtra("users",users);
                    setResult(Activity.RESULT_OK,intent);
                }
                finish();
            }
        });
        etSearch.setOnXTextChangeListener(new CustomEditText.OnXTextChangeListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                doSearch(s.toString());
            }
        });
        resetUserInfos(chooseUsers);
    }

    private void doSearch(String keyword) {
        if(Common.isEmpty(chooseUsers)){
            return;
        }
        if (!StringUtils.isEmpty(keyword)) {
            List<UserInfo> list = new ArrayList<>();
            for (UserInfo user : chooseUsers) {
                if (user.isMatch(keyword)) {
                    list.add(user);
                }
            }
            resetUserInfos(list);
        } else {
            resetUserInfos(chooseUsers);
        }
    }


    private void resetUserInfos(List<UserInfo> list){
        sectionList.clear();
        if(!Common.isEmpty(list)){
            if (list.size() > 1) {
                Collections.sort(list, new Comparator<UserInfo>() {
                    @Override
                    public int compare(UserInfo u1, UserInfo u2) {
                        if (!StringUtils.isEmpty(u1.displayName_full_py) && !StringUtils.isEmpty(u2.displayName_full_py)) {
                            return u1.displayName_full_py.compareTo(u2.displayName_full_py);
                        }
                        return 0;
                    }
                });
            }
            //生成a-z hash
            Map<String, List<UserInfo>> sectionMap = new HashMap<>();
            for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
                sectionMap.put(azIndex, new ArrayList<>());
            }
            //插入userinfo
            for (UserInfo user : list) {
                if (!StringUtils.isEmpty(user.displayName_full_py)) {
                    if (sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))) != null) {
                        sectionMap.get(String.valueOf(user.displayName_full_py.toUpperCase().charAt(0))).add(user);
                    } else {
                        sectionMap.get("#").add(user);
                    }
                } else {
                    sectionMap.get("#").add(user);
                }
            }
            //ui数据
            for (String azIndex : SideIndexBar.DEFAULT_INDEX_ITEMS_1) {
                if (sectionMap.get(azIndex).size() > 0) {
                    sectionList.add(new Section(true, new SectionInfo(azIndex)));
                    for (UserInfo user : sectionMap.get(azIndex)) {
                        sectionList.add(new Section(false, user));
                    }
                }
            }
        }
        //刷新页面
        contactChooseAdapter.notifyDataSetChanged();
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_remove_circle_setting_users;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    protected boolean isHaveEventBus() {
        return true;
    }
}
